package com.ds.api.interceptor;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ds.api.dao.UserKeyMapper;
import com.ds.api.model.UserKey;
import com.ds.api.utils.Content;
import com.google.gson.Gson;

/**
 * <pre>
 * 权限拦截器，拦截请求路径：/**
 * 此拦截器主要是验证客户端是否合法，同时处理注解@Login。
 * 
 * 
 * @author xiangwei
 *
 */
public class SecurityInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private UserKeyMapper mapper;

	/**不拦截URL*/
	public static final String[] UNCHECK_URL = new String[] { "/user/register","/user/checkUser",
	        "/user/login","/send/message","/user/thirdRegister","/user/forget","/verify/test" ,
	        "/type/query","/type/add","/type/advert",
	        "/user/thirdLogin","/type/get","/sheet/list","/type/queryTree","/user/search"
	        };


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.setCharacterEncoding("utf-8");

		for (String url : SecurityInterceptor.UNCHECK_URL) {
			if (url.equals(request.getRequestURI())) {
				return super.preHandle(request, response, handler);
			}
		}
		/**
		 * 检查key的合法性
		 */
		String key=request.getParameter("key");
		key = key==null?"":key;
		UserKey exp = new UserKey();
		exp.setUidKey(key);
		exp.setIsActive("0");
		List<UserKey> keyList = mapper.query(exp);
		if (keyList.size() > 0) {
			UserKey keyBean = keyList.get(0);
			keyBean.setUpdateTime(new Date());
			mapper.updateByPrimaryKeySelective(keyBean);
			request.setAttribute("USER_ID", keyBean.getFkUserBaseinfoId()==null?"": keyBean.getFkUserBaseinfoId());
			return super.preHandle(request, response, handler);
		}else{
			Map<String, String> gsonMap = new HashMap<String, String>();
			gsonMap.put("key", "");
			gsonMap.put("result", Content.RESULT_ERROR);
			gsonMap.put("err_str", "密钥已失效或密钥错误，请重新登录！");
			PrintWriter out = response.getWriter();
			Gson gson = new Gson();
			out.write(gson.toJson(gsonMap));
			out.flush();
			out.close();

		}
		return false;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
			Object handler, Exception ex) throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}



}
